<template>
  <q-page class="dashboard-page">
    <!-- 页面标题和操作按钮 -->
    <div class="header-section">
      <div>
        <h1 class="text-gradient">系统仪表盘</h1>
        <p class="subtitle">实时监控系统运行状态</p>
      </div>
      <div class="action-buttons">
        <q-btn
          color="primary"
          icon="refresh"
          label="刷新数据"
          @click="refreshData"
          :loading="refreshing"
          rounded
          unelevated
        />
        <q-btn color="grey-7" icon="settings" round unelevated @click="showSettings" />
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-grid">
      <stat-card
        v-for="(stat, index) in stats"
        :key="`stat-${index}`"
        v-bind="stat"
        class="stat-item"
      />
    </div>

    <!-- 图表和活动区域 -->
    <div class="main-content-grid">
      <!-- 主要图表 -->
      <q-card class="chart-card">
        <q-card-section class="chart-header">
          <div class="chart-title">
            <h2>系统访问趋势</h2>
            <p>最近{{ chartTimeRange }}数据</p>
          </div>
          <q-select
            v-model="chartTimeRange"
            :options="timeRangeOptions"
            dense
            outlined
            dark
            borderless
            class="time-selector"
          />
        </q-card-section>
        <div class="chart-container">
          <line-chart :chart-data="accessChartData" :options="chartOptions" />
        </div>
      </q-card>

      <!-- 最近活动 -->
      <q-card class="activity-card">
        <q-card-section class="activity-header">
          <h2>最近活动</h2>
          <div class="notification-badge">
            <q-badge color="red" rounded floating>{{ recentActivities.length }}</q-badge>
            <q-icon name="notifications" />
          </div>
        </q-card-section>
        <div class="activity-list-container">
          <q-list class="activity-list">
            <q-item
              v-for="(activity, index) in recentActivities"
              :key="`activity-${index}`"
              class="activity-item"
              :class="`activity-${activity.color}`"
              clickable
              v-ripple
              @click="handleActivityClick(activity)"
            >
              <q-item-section avatar>
                <q-avatar :color="activity.color" text-color="white" :icon="activity.icon" />
              </q-item-section>
              <q-item-section>
                <q-item-label class="activity-title">{{ activity.action }}</q-item-label>
                <q-item-label caption class="activity-time">{{ activity.time }}</q-item-label>
              </q-item-section>
              <q-item-section side>
                <q-icon name="chevron_right" />
              </q-item-section>
            </q-item>
          </q-list>
        </div>
        <q-card-actions class="card-actions">
          <q-btn flat color="primary" label="查看全部" @click="showAllActivities" />
        </q-card-actions>
      </q-card>
    </div>

    <!-- 系统资源监控 -->
    <div class="resource-grid">
      <q-card class="resource-card">
        <q-card-section class="resource-header">
          <h2>CPU & 内存使用率</h2>
          <div class="resource-actions">
            <q-chip dense color="red" text-color="white">
              <q-avatar icon="warning" color="red" size="xs" />
              实时监控
            </q-chip>
            <q-btn flat dense round icon="refresh" color="white" @click="refreshResources" />
          </div>
        </q-card-section>
        <div class="chart-container">
          <bar-chart :chart-data="resourceChartData" :options="resourceChartOptions" />
        </div>
      </q-card>

      <q-card class="storage-card">
        <q-card-section class="storage-header">
          <div class="storage-info">
            <h2>存储空间</h2>
            <p>已使用 {{ storageUsage }}% / 剩余 {{ 100 - storageUsage }}%</p>
          </div>
          <q-circular-progress
            show-value
            :value="storageUsage"
            size="40px"
            :thickness="0.2"
            color="warning"
            track-color="grey-3"
            class="storage-progress"
          >
            {{ storageUsage }}%
          </q-circular-progress>
        </q-card-section>
        <div class="chart-container">
          <pie-chart :chart-data="storageChartData" :options="pieChartOptions" />
        </div>
      </q-card>
    </div>

    <!-- 设置对话框 -->
    <q-dialog v-model="settingsVisible">
      <q-card class="settings-dialog">
        <q-card-section>
          <div class="dialog-header">
            <h3>仪表盘设置</h3>
            <q-btn flat round dense icon="close" v-close-popup />
          </div>
        </q-card-section>
        <q-card-section class="settings-content">
          <q-toggle v-model="darkMode" label="暗黑模式" />
          <q-toggle v-model="autoRefresh" label="自动刷新数据" />
          <q-input
            v-model.number="refreshInterval"
            type="number"
            label="刷新间隔(秒)"
            min="10"
            max="3600"
          />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn flat label="取消" color="grey" v-close-popup />
          <q-btn flat label="保存" color="primary" @click="saveSettings" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useQuasar } from 'quasar'
import StatCard from './components/StatCard.vue'
import LineChart from './components/LineChart.vue'
import BarChart from './components/BarChart.vue'
import PieChart from './components/PieChart.vue'

const $q = useQuasar()

// 响应式状态
const refreshing = ref(false)
const settingsVisible = ref(false)
const darkMode = ref(false)
const autoRefresh = ref(false)
const refreshInterval = ref(60)
const chartTimeRange = ref('30天')
const timeRangeOptions = ['7天', '30天', '90天', '1年']
const storageUsage = ref(75)

// 计算属性
const storageChartData = computed(() => ({
  labels: ['已使用', '可用空间'],
  datasets: [
    {
      data: [storageUsage.value, 100 - storageUsage.value],
      backgroundColor: ['#FFCE56', '#4BC0C0'],
      borderWidth: 1,
    },
  ],
}))

// 统计数据
const stats = ref([
  { title: '总用户数', value: '2,845', change: '+12%', icon: 'person', color: 'primary' },
  { title: '今日访问量', value: '1,284', change: '+5.2%', icon: 'visibility', color: 'green' },
  { title: '待处理事项', value: '24', change: '-3', icon: 'assignment', color: 'orange' },
  { title: '系统警报', value: '3', change: '+1', icon: 'warning', color: 'red' },
])

// 图表数据
const accessChartData = ref(generateChartData(30))
const resourceChartData = ref({
  labels: ['CPU使用率', '内存使用率'],
  datasets: [
    {
      label: '使用率(%)',
      data: [65, 45],
      backgroundColor: ['#FF6384', '#36A2EB'],
      borderWidth: 1,
      borderRadius: 4,
    },
  ],
})

// 图表配置
const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false },
    tooltip: {
      backgroundColor: '#424242',
      titleColor: '#fff',
      bodyColor: '#fff',
      borderColor: 'rgba(255,255,255,0.1)',
      borderWidth: 1,
      padding: 12,
      usePointStyle: true,
    },
  },
  scales: {
    y: {
      beginAtZero: true,
      grid: { color: 'rgba(0,0,0,0.05)' },
      ticks: { color: '#616161' },
    },
    x: {
      grid: { display: false },
      ticks: { color: '#616161' },
    },
  },
}

const resourceChartOptions = { ...chartOptions }
const pieChartOptions = {
  ...chartOptions,
  plugins: {
    ...chartOptions.plugins,
    legend: {
      position: 'right',
      labels: {
        color: '#616161',
        padding: 16,
        usePointStyle: true,
        pointStyle: 'circle',
      },
    },
  },
}

// 活动数据
const recentActivities = ref([
  { action: '管理员登录系统', time: '5分钟前', icon: 'login', color: 'primary' },
  { action: '用户张三更新了个人信息', time: '12分钟前', icon: 'edit', color: 'green' },
  { action: '系统备份完成', time: '30分钟前', icon: 'backup', color: 'blue' },
  { action: '新用户李四注册', time: '1小时前', icon: 'person_add', color: 'orange' },
  { action: '系统检测到异常登录', time: '2小时前', icon: 'warning', color: 'red' },
])

// 方法
function generateChartData(days) {
  return {
    labels: Array.from({ length: days }, (_, i) => `${i + 1}日`),
    datasets: [
      {
        label: '访问量',
        data: Array.from({ length: days }, () => Math.floor(Math.random() * 1000) + 500),
        borderColor: '#1976D2',
        backgroundColor: 'rgba(25, 118, 210, 0.1)',
        tension: 0.4,
        fill: true,
        borderWidth: 2,
        pointRadius: 3,
        pointBackgroundColor: '#1976D2',
      },
    ],
  }
}

function refreshData() {
  refreshing.value = true
  setTimeout(() => {
    stats.value.forEach((stat) => {
      if (stat.title === '今日访问量') {
        stat.value = (Math.floor(Math.random() * 500) + 1000).toLocaleString()
        stat.change = `${Math.random() > 0.5 ? '+' : '-'}${(Math.random() * 10).toFixed(1)}%`
      }
    })
    accessChartData.value = generateChartData(
      chartTimeRange.value === '7天'
        ? 7
        : chartTimeRange.value === '30天'
          ? 30
          : chartTimeRange.value === '90天'
            ? 90
            : 365,
    )
    refreshing.value = false
    showNotification('数据已刷新', 'positive')
  }, 800)
}

function refreshResources() {
  resourceChartData.value.datasets[0].data = [
    Math.floor(Math.random() * 100),
    Math.floor(Math.random() * 100),
  ]
  showNotification('资源数据已更新', 'info')
}

function showSettings() {
  settingsVisible.value = true
}

function saveSettings() {
  settingsVisible.value = false
  showNotification('设置已保存', 'positive')
}

function handleActivityClick(activity) {
  console.log('Activity  clicked:', activity)
  // 实际项目中这里可以跳转到相关页面
}

function showAllActivities() {
  console.log('Show  all activities')
  // 实际项目中这里可以跳转到活动日志页面
}

function showNotification(message, type) {
  $q.notify({
    type,
    message,
    position: 'top-right',
    timeout: 1000,
  })
}

// 监听器
watch(chartTimeRange, (newVal) => {
  accessChartData.value = generateChartData(
    newVal === '7天' ? 7 : newVal === '30天' ? 30 : newVal === '90天' ? 90 : 365,
  )
})

watch(darkMode, (val) => {
  $q.dark.set(val)
})

// 生命周期钩子
onMounted(() => {
  refreshData()
  if (autoRefresh.value) {
    setInterval(refreshData, refreshInterval.value * 1000)
  }
})
</script>

<style lang="scss" scoped>
.dashboard-page {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
  min-height: 100vh;
  transition: all 0.3s ease;

  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .text-gradient {
      background: linear-gradient(90deg, #1976d2 0%, #2196f3 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      font-size: 2rem;
      font-weight: 700;
      margin: 0;
      letter-spacing: 0.5px;
    }

    .subtitle {
      color: #616161;
      font-size: 0.875rem;
      margin: 4px 0 0;
    }

    .action-buttons {
      display: flex;
      gap: 8px;
    }
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 16px;
    margin-bottom: 24px;

    .stat-item {
      transition:
        transform 0.3s ease,
        box-shadow 0.3s ease;

      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1) !important;
      }
    }
  }

  .main-content-grid {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 16px;
    margin-bottom: 24px;

    @media (max-width: 1024px) {
      grid-template-columns: 1fr;
    }

    .chart-card,
    .activity-card {
      border-radius: 12px;
      overflow: hidden;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12) !important;
      }
    }

    .chart-header {
      background: linear-gradient(90deg, #1976d2 0%, #2196f3 100%);
      color: white;
      padding: 16px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h2 {
        margin: 0;
        font-size: 1.25rem;
      }

      p {
        margin: 4px 0 0;
        font-size: 0.875rem;
        opacity: 0.8;
      }

      .time-selector {
        width: 120px;

        :deep(.q-field__control) {
          height: 32px;
          min-height: auto;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 4px;
        }

        :deep(.q-field__native) {
          min-height: auto;
          padding: 0 8px;
          color: white;
        }
      }
    }

    .activity-header {
      background: #1976d2;
      color: white;
      padding: 16px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h2 {
        margin: 0;
        font-size: 1.25rem;
      }

      .notification-badge {
        position: relative;
        display: flex;
        align-items: center;

        .q-badge {
          position: absolute;
          top: -8px;
          right: -8px;
        }
      }
    }

    .chart-container {
      height: 300px;
      padding: 16px;
    }

    .activity-list-container {
      max-height: 400px;
      overflow-y: auto;
      padding: 8px 0;
    }

    .activity-item {
      padding: 12px 16px;
      transition: all 0.3s ease;
      border-left: 3px solid transparent;

      &:hover {
        background-color: rgba(0, 0, 0, 0.02);
        transform: translateX(4px);
      }

      &.activity-primary {
        border-left-color: #1976d2;
      }
      &.activity-green {
        border-left-color: #4caf50;
      }
      &.activity-blue {
        border-left-color: #2196f3;
      }
      &.activity-orange {
        border-left-color: #ff9800;
      }
      &.activity-red {
        border-left-color: #f44336;
      }

      .activity-title {
        font-weight: 500;
      }

      .activity-time {
        color: #616161;
      }
    }

    .card-actions {
      border-top: 1px solid rgba(0, 0, 0, 0.1);
      padding: 8px 16px;
    }
  }

  .resource-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }

    .resource-card,
    .storage-card {
      border-radius: 12px;
      overflow: hidden;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12) !important;
      }
    }

    .resource-header {
      background: #37474f;
      color: white;
      padding: 16px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h2 {
        margin: 0;
        font-size: 1.25rem;
      }

      .resource-actions {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }

    .storage-header {
      background: #006064;
      color: white;
      padding: 16px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h2 {
        margin: 0;
        font-size: 1.25rem;
      }

      p {
        margin: 4px 0 0;
        font-size: 0.875rem;
        opacity: 0.8;
      }

      .storage-progress {
        margin-left: 16px;
      }
    }
  }

  .settings-dialog {
    width: 100%;
    max-width: 500px;
    border-radius: 12px;

    .dialog-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 1.25rem;
      }
    }

    .settings-content {
      display: flex;
      flex-direction: column;
      gap: 16px;
      padding: 16px 24px;
    }
  }

  // 自定义滚动条
  ::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  ::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
    border-radius: 3px;
  }

  ::-webkit-scrollbar-thumb {
    background: rgba(0, 0, 0, 0.2);
    border-radius: 3px;

    &:hover {
      background: rgba(0, 0, 0, 0.3);
    }
  }
}

// 暗黑模式样式
.body--dark {
  .dashboard-page {
    background: linear-gradient(135deg, #121212 0%, #1e1e1e 100%);

    .chart-card,
    .activity-card,
    .resource-card,
    .storage-card {
      background-color: #2d2d2d;
    }

    .activity-item:hover {
      background-color: rgba(255, 255, 255, 0.05);
    }

    .card-actions {
      border-top-color: rgba(255, 255, 255, 0.1);
    }
  }
}
</style>
